import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import time
import sqlite3
import os
from utils.logger_config import logger

app = FastAPI(title="My Web Service")  # 文档标题仍然固定

@app.middleware("http")
async def log_requests(request: Request, call_next):
    start_time = time.time()
    client_host = request.client.host  # 客户端 IP
    method = request.method
    url = str(request.url)

    try:
        response = await call_next(request)
    except Exception as e:
        # 获取路由 endpoint 名称
        endpoint_name = request.scope.get("endpoint").__name__ if request.scope.get("endpoint") else "unknown"
        logger.exception(f"[{client_host}] 请求异常: {method} {url} - endpoint: {endpoint_name} - {e}")
        return JSONResponse(status_code=500, content={"detail": "Internal Server Error"})

    process_time = (time.time() - start_time) * 1000
    endpoint_name = request.scope.get("endpoint").__name__ if request.scope.get("endpoint") else "unknown"
    logger.info(f"[{client_host}] {method} {url} - endpoint: {endpoint_name} - {response.status_code} - {process_time:.2f}ms")
    return response

# ==========================
# 示例接口
# ==========================
@app.get("/")
def read_root():
    return {"message": "Hello, World!"}

@app.get("/items/{item_id}")
def get_item(item_id: int):
    return {"item_id": item_id}

# 使用绝对路径，保证 FastAPI 启动时能正确找到数据库
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DB_PATH = os.path.join(BASE_DIR, "db", "my_database.db")

def get_connection():
    return sqlite3.connect(DB_PATH)

# 查询所有用户
@app.get("/users")
def get_users():
    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT id, name FROM users")
    rows = cursor.fetchall()
    conn.close()
    return {"users": [{"id": row[0], "name": row[1]} for row in rows]}

# 插入新用户
@app.post("/users/{name}")
def add_user(name: str):
    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute("INSERT INTO users (name) VALUES (?)", (name,))
    conn.commit()
    conn.close()
    return {"message": f"User '{name}' added successfully"}
# ==========================
# main 方法入口
# ==========================
if __name__ == "__main__":
    logger.info("启动 Web 服务")
    uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
